package com.mazaiting.face.ui.utils;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.media.MediaPlayer;
import com.mazaiting.face.ui.FaceDetectActivity;
import com.mazaiting.log.L;

/**
 * VolumeUtil
 * 描述:系统音量监听
 */
public class VolumeUtil {

    /**
     * 判断是否开启声音
     * @param context 上下文
     * @return true: 开启; false: 关闭
     */
    public static boolean isSound(Context context) {
        // 获取声音管理者
        AudioManager am = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
        // 获取媒体音量
        int vol = am.getStreamVolume(AudioManager.STREAM_MUSIC);
        return vol > 0;
    }


    /**
     * 播放声音
     * @param context 上下文
     * @param resId 资源 ID
     */
    public static void playSound(Context context, int resId) {
        MediaPlayer mediaPlayer = MediaPlayer.create(context, resId);
        mediaPlayer.start();
    }


    /**
     * 声音广播
     */
    public static class VolumeReceiver extends BroadcastReceiver {
        /**
         * 声音回调
         */
        private VolumeCallback callback;

        public VolumeReceiver(VolumeCallback callback) {
            this.callback = callback;
        }

        @Override
        public void onReceive(Context context, Intent intent) {
            L.d(intent.getAction());
            if ("android.media.VOLUME_CHANGED_ACTION".equals(intent.getAction())
                    && callback != null) {
                callback.volumeChanged();
            }
        }
    }

    /**
     * 注册声音广播
     * @param context 上下文
     * @param callback 回调
     * @return 广播
     */
    public static BroadcastReceiver registerVolumeReceiver(Context context, VolumeCallback callback) {
        // 声明声音广播
        VolumeReceiver mVolumeReceiver = null;
        try {
            // 初始化
            mVolumeReceiver = new VolumeReceiver(callback);
            // 设置过滤器
            IntentFilter filter = new IntentFilter();
            // 添加动作
            filter.addAction("android.media.VOLUME_CHANGED_ACTION");
            // 注册广播
            context.registerReceiver(mVolumeReceiver, filter);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return mVolumeReceiver;
    }

    /**
     * 取消注册声音广播
     * @param context 上下文
     * @param receiver 广播
     */
    public static void unRegisterVolumeReceiver(Context context, BroadcastReceiver receiver) {
        try {
            if (null != context&& null != receiver) {
                context.unregisterReceiver(receiver);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 声音回调
     */
    public interface VolumeCallback {
        /**
         * 声音改变
         */
        void volumeChanged();
    }
}
